<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <searchrevealing>
        <el-tabs v-model="activeTab">
          <el-tab-pane label="供应商提报" name="qualityControl">
            <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="88px">
              <el-form-item label="商品编码" prop="styleCode">
                <el-input v-model="queryParams.styleCode" placeholder="请输入商品编码" clearable style="width: 220px"
                  @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="供应商" prop="supplierName">
                <!-- <el-select v-model="queryParams.supplierName" placeholder="请选择供应商" clearable style="width: 220px">
                  <el-option v-for="dict in hm_supplier_type" :key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select> -->
                <el-select-v2 v-model="queryParams.supplierName" filterable clearable :options="supplierNameOptions"
                  placeholder="请选择供应商" style="width: 220px" />
              </el-form-item>
              <el-form-item label="类目" prop="category">
                <el-cascader ref="categoryRef" v-model="queryParams.category" :props="categoryProps"
                  style="width: 220px" @change="handleChange" placeholder="请选择类目" />
              </el-form-item>
              <el-form-item label="商品名称" prop="styleName">
                <el-input v-model="queryParams.styleName" placeholder="请输入商品名称" clearable style="width: 220px"
                  @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="合作方式" prop="cooperationMode">
                <el-select v-model="queryParams.cooperationMode" placeholder="请选择合作方式" clearable style="width: 220px">
                  <el-option v-for="dict in hm_cooperation_mode" :key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="招商部" prop="recruiterDept">
                <el-select v-model="queryParams.recruiterDept" placeholder="请选择招商部" clearable @change="deptChange"
                  style="width: 220px">
                  <el-option v-for="dict in deptList" :key="dict.deptId" :label="dict.deptName" :value="dict.deptId" />
                </el-select>
              </el-form-item>
              <el-form-item label="招商员" prop="recruiter">
                <el-select v-model="queryParams.recruiter" placeholder="请选择招商员" clearable style="width: 220px">
                  <el-option v-for="dict in recruiterList" :key="dict.userId" :label="dict.userName"
                    :value="dict.userId" />
                </el-select>
              </el-form-item>
              <el-form-item label="佣金" prop="commission">
                <el-input v-model.number="queryParams.commission" placeholder="请输入佣金" style="width: 220px" />
              </el-form-item>
              <el-form-item label="价格" prop="minPrice">
                <el-input v-model="queryParams.minPrice" class="priceInput" style="width: 97px; margin-right: 10px" @keyup.enter="handleQuery"/>-
                <el-input v-model="queryParams.maxPrice" class="priceInput" ref="maxPrice"
                  style="width: 97px; margin-left: 10px" @keyup.enter="handleQuery"/>
              </el-form-item>
              <el-form-item label="审核状态" prop="auditStatu">
                <el-select v-model="queryParams.auditStatu" placeholder="请选择审核状态" clearable @change="auditStatuChange"
                  style="width: 220px">
                  <el-option v-for="dict in auditStatusList" :key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="合同状态" prop="contractStatus">
                <el-select v-model="queryParams.contractStatus" placeholder="请选择合同状态" clearable style="width: 220px">
                  <el-option v-for="dict in hm_contract" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="资审发起人" prop="auditor">
                <el-select v-model="queryParams.auditor" placeholder="请选择资审发起人" clearable style="width: 220px">
                  <el-option v-for="dict in hm_quality" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-form>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </searchrevealing>
    </transition>
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" @click="handleIntention">我的意向</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" :data="supplierAddProductsList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="供应商" align="center" prop="supplierName" />
        <el-table-column label="商品名称" align="center" prop="styleName">
          <template #default="scope">
            <div class="color_theme">{{ scope.row.styleName }}</div>
          </template>
        </el-table-column>
        <el-table-column label="商品编码" align="center" prop="styleCode" />
        <el-table-column label="商品主图" align="center" prop="productImage" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.productImage" :width="50" :height="50" />
          </template>
        </el-table-column>
        <el-table-column label="类目" align="center" prop="categoryName">

        </el-table-column>
        <el-table-column label="招商员" align="center" prop="recruiter" />
        <el-table-column label="品牌" align="center" prop="brand">
          <template #default="scope">
            {{ handleFilterBrand(scope.row.brand, brandList) }}
          </template>
        </el-table-column>
        <el-table-column label="店铺名称" align="center" prop="storeName" />
        <el-table-column label="在售链接" align="center" prop="saleLink" show-overflow-tooltip>
          <template #default="scope">
            <el-link :href="scope.row.saleLink" type="primary" target="_blank">{{ scope.row.saleLink }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="意向合作主播" align="center" prop="likePerson">
          <template #default="scope">
            <dict-tag :options="hm_anchor" :value="scope.row.likePerson" />
          </template>
        </el-table-column>
        <el-table-column label="直播机制" align="center" prop="liveStreamingMechanism" />
        <el-table-column label="佣金" align="center" prop="commission" />
        <el-table-column label="状态" align="center" prop="auditStatus">
          <template #default="scope">
            <div>{{ auditStatusNameById(scope.row.auditStatus) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="商品卖点" align="center" prop="sellingPoints" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleInfo(scope.row)" class="color_theme"> 查看详情</el-button>
            <el-button :disabled="scope.row.auditStatus == '5' || scope.row.auditStatus == '4'" link type="primary"
              @click="handleUpdate(scope.row)" class="color_theme" style="margin-left: 0px !important"> {{
                (scope.row.auditStatus == '2' || scope.row.auditStatus == '3') ? '重新审核' : '资质审核' }}</el-button>
            <el-button link type="primary" @click="handleAdd(scope.row)" class="color_theme"
              style="margin-left: 0px !important">添加意向</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!--商品详情抽屉 -->
    <commoditydetails @doClose="commoditydetailsClose" :commoditydetailsData="commoditydetailsData"
      :dialogInfoVisible="dialogInfoVisible"></commoditydetails>
    <!-- 资质审核 -->
    <examine @doClose="examineClose" :examineData="examineData" :examineVisible="examineVisible"></examine>
    <!-- 我的意向 -->
    <intention @doClose="intentionClose" :intentionVisible="intentionVisible">
    </intention>
  </div>
</template>
<script setup name="QualityControl" lang="ts">
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_user_sex } = toRefs<any>(proxy?.useDict('sys_user_sex'));
import { QualityControlForm, QualityControlQuery } from '@/api/group/qualityControl/types';
import { listSupplierAddProduct, getSupplierAddProducts, getproductscategorychildlistbypid } from '@/api/system/supplierAddProducts';
import { SupplierAddProductsVO } from '@/api/system/supplierAddProducts/types';
import commoditydetails from '../components/commoditydetails.vue'
import { anchorSupplierIntention, getDeptList, getUserById } from '@/api/group/qualityControl'
import examine from './components/examine.vue'
import intention from './components/intention.vue'
import { BrandVO } from '@/api/system/brand/types';
import { listBrand } from '@/api/system/brand';
import { auditStatusNameById } from '@/utils/auditStatusFilter'
import { hmSupplierList } from '@/api/group/supplier/index'
const { hm_category } = toRefs<any>(proxy?.useDict('hm_category'));
const { hm_anchor } = toRefs<any>(proxy?.useDict('hm_anchor'));
const { hm_cooperation_mode } = toRefs<any>(proxy?.useDict('hm_cooperation_mode'));
const { hm_supplier_type } = toRefs<any>(proxy?.useDict('hm_supplier_type'));
const { hm_contract } = toRefs<any>(proxy?.useDict('hm_contract'));
const { hm_quality } = toRefs<any>(proxy?.useDict('hm_quality'));

const supplierNameOptions = ref<any[]>([])
const activeTab = ref('qualityControl');
const showSearch = ref(true);
const loading = ref(true);
const total = ref(0);
const supplierAddProductsList = ref<SupplierAddProductsVO[]>([]);
const queryFormRef = ref<ElFormInstance>();
const ids = ref<Array<string | number>>([]);
const commoditydetailsData = ref<QualityControlForm>({})
const examineData = ref<QualityControlForm>({})
const dialogInfoVisible = ref(false)
const examineVisible = ref(false)
const intentionVisible = ref(false)
const brandList = ref<BrandVO[]>([]);
const deptList = ref<{ deptId: string; deptName: string; }[]>([])
const recruiterList = ref<{ userId: string; userName: string; }[]>([])
const categoryRef = ref();

const initFormData: QualityControlForm = {
  id: undefined,
  auditing: undefined
};
const data = reactive<PageData<QualityControlForm, QualityControlQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    styleCode: undefined,
    category: undefined,
    supplierName: undefined,
    styleName: undefined,
    cooperationMode: undefined,
    recruiterDept: undefined,
    recruiter: undefined,
    price: undefined,
    contractStatus: undefined,
    auditor: undefined,
    commission: undefined,
    auditStatus: undefined,
    auditStatu: undefined
  },
  rules: {}
});
const { queryParams, form, rules } = toRefs(data);

const auditStatusList = reactive([
  { label: '待审核', value: '1' },
  { label: '未通过', value: '2' },
  { label: '审核通过', value: '3' },
  { label: '待寄样', value: '4' },
  { label: '无货', value: '5' },
  { label: '寄样中', value: '6' },
  { label: '已入库', value: '7' },
  { label: '补样邀约', value: '8' },
  { label: '破损补样邀约', value: '9' },
  { label: '招商部退还', value: '10' },
]);

/**
 * 获取供应商列表
 */
 const getHmSupplierList = async() =>{
    const res = await hmSupplierList()
    supplierNameOptions.value = res.rows.map((item: any)=>(
        {
            label: item.supplierName,
            value: item.userId
        }
    ))
}

// 类目请求方法封装
const ategoryQuest = (pid: string | number, level: any, resolve: (data: any) => void) => {
  getproductscategorychildlistbypid({ pid: pid }).then(res => {
    const datas = res.rows.map((value: { categoryId: string, categoryName: string }) => ({
      value: value.categoryId,
      label: value.categoryName,
      // leaf: level >= 3
    }));
    resolve(datas);
  })
}

// 筛选类目change事件
const handleChange = (val: [string, string, string, string]) => {
  if (val) {

    categoryRef.value.togglePopperVisible()
    queryParams.value.category = val[val.length - 1]
    queryParams.value.firstCategory = val[0]
    queryParams.value.secondCategory = val[1]
    queryParams.value.thirdCategory = val[2]
    queryParams.value.fourthCategory = val[3]
  }
}

// 类目props
const categoryProps = reactive({
  lazy: true,
  checkStrictly: true,
  lazyLoad(node: any, resolve: (data: any) => void) {
    const { level } = node
    const pid = !level ? 0 : node.value
    ategoryQuest(pid, level, resolve)
  }
})

/**
 * 品牌检索value
 * @param para 
 * @param dict 
 */
const handleFilterBrand = (para: string | number | undefined, dict: Array<any>) => {
  let _label = '';
  dict.forEach((item: any) => {
    if (item.id == String(para)) {
      _label = item.brandName;
    }
  });
  return _label;
};

/**
 * 获取品牌信息
 */
const getListBrand = async () => {
  const res = await listBrand()
  brandList.value = res.rows;
}

/**
 * 获取招商部门信息
 */
const getDeptLists = async () => {
  const res = await getDeptList({ parentId: '1782395704411734018' })
  deptList.value = res.data
}

/**
 *  根据招商部获取招商员
 */
const deptChange = async (event: string) => {
  if (event) {
    const res = await getUserById(event)
    recruiterList.value = res.data
    queryParams.value.recruiter = undefined
  } else {
    recruiterList.value = []
    queryParams.value.recruiter = undefined
  }
}

/**
 * 审核状态搜索
 */
const auditStatuChange = (value: string) => {
  queryParams.value.pageNum = 1;
  queryParams.value.auditStatus = value;
};

/** 查询供应商添加商品列表 */
const getList = async () => {
  try {
    loading.value = true;
    const res = await listSupplierAddProduct(queryParams.value);
    supplierAddProductsList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  } catch (e) {
  } finally {
    loading.value = false;
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.auditStatus = '1,2,3,4,5,6,7,8,9';
  handleQuery();
};
/** 多选框选中数据 */
const handleSelectionChange = (selection: SupplierAddProductsVO[]) => {
  ids.value = selection.map((item) => item.id);
};

/** 查看商品详情 */
const handleInfo = (row?: SupplierAddProductsVO) => {
  nextTick(async () => {
    const _id = row?.id || ids.value[0];
    const res: any = await getSupplierAddProducts(_id);
    dialogInfoVisible.value = true;
    commoditydetailsData.value = res.data
  });
};
/** 商品详情关闭 */
const commoditydetailsClose = () => {
  dialogInfoVisible.value = false;
}
/** 资质审核 */
const handleUpdate = (row?: SupplierAddProductsVO) => {
  nextTick(async () => {
    const _id = row?.id || ids.value[0];
    const res: any = await getSupplierAddProducts(_id);
    examineVisible.value = true;
    examineData.value = res.data
  });
};
/** 资质审核关闭 */
const examineClose = () => {
  examineVisible.value = false;
  getList();
}
/** 添加意向 */
const handleAdd = async (row?: SupplierAddProductsVO) => {
  const _ids = row?.id;
  const _names = row?.styleName;
  await proxy?.$modal.confirm('是否确认添加意向，商品名称为"' + _names + '"的数据项？').finally(() => (loading.value = false));
  await anchorSupplierIntention({ productsId: _ids });
  proxy?.$modal.msgSuccess('添加意向成功');
  await getList();
};
/** 我的意向 */
const handleIntention = async () => {
  intentionVisible.value = true;
  // intentionData.value = supplierAddProductsList.value;
}
/** 我的意向关闭 */
const intentionClose = () => {
  intentionVisible.value = false;
  getList();
};
onMounted(() => {
  queryParams.value.auditStatus = '1,2,3,4,5,6,7,8,9';
  queryParams.value.pageNum = 1;
  getDeptLists();
  getListBrand();
  getHmSupplierList();
  getList();
});
</script>
<style lang="scss" scoped>
.mb96 {
  margin-bottom: 96px;
}

.color_theme {
  // color: rgba(1, 147, 255) !important;
}
</style>